<template>
  <div class="component-upload-image">
    <el-upload
      :action="uploadImgUrl"
      list-type="text"
      :limit="limit"
      :on-success="handleUploadSuccess"
      :before-upload="handleBeforeUpload"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      ref="imageUpload"
      :on-remove="handleDelete"
      :show-file-list="true"
      :headers="headers"
      :file-list="fileList"
    >
      <el-button type="primary" icon="el-icon-upload">点击上传</el-button>
    </el-upload>

    <!-- 上传提示 -->
    <div class="el-upload__tip" slot="tip" v-if="showTip">
      请上传
      <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
      <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
      的文件
    </div>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";

export default {
  name: "PdfUpload",
  props: {
    value: [String, Object, Array],
    limit: {
      type: Number,
      default: 1,
    },
    fileSize: {
      type: Number,
      default: 10,
    },
    fileType: {
      type: Array,
      default: () => ["pdf"],
    },
    isShowTip: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: []
    };
  },
  watch: {
    value: {
      handler(val) {
        console.log("PdfUpload value changed:", val);
        if (val) {
          const list = Array.isArray(val) ? val : [val];
          this.fileList = list.map(item => ({
            name: item,
            url: this.baseUrl + item
          }));
        } else {
          this.fileList = [];
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  methods: {
    handleBeforeUpload(file) {
      let isPdf = false;
      if (this.fileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isPdf = this.fileType.some(type => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isPdf = file.type.indexOf("application/pdf") > -1;
      }

      if (!isPdf) {
        this.$message.error(`文件格式不正确, 请上传${this.fileType.join("/")}文件格式文件!`);
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
    },
    handleExceed() {
      this.$message.error(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    handleUploadSuccess(response, file) {
      console.log("Upload response:", response);
      if (response.code === 200) {
        this.$emit('input', response.url); // 将上传的文件URL传递给父组件
        this.$message.success("文件上传成功");
      } else {
        this.$message.error(response.message);
      }
    },
    handleDelete(file) {
      const findex = this.fileList.map(f => f.name).indexOf(file.name);
      if (findex > -1) {
        this.fileList.splice(findex, 1);
        this.$emit("input", this.fileList.map(f => f.url).join(','));
      }
    },
    handleUploadError() {
      this.$message.error("上传文件失败，请重试");
    }
  }
};
</script>

<style scoped lang="scss">
// .el-upload--picture-card 控制加号部分
::v-deep.hide .el-upload--picture-card {
  display: none;
}
// 去掉动画效果
::v-deep .el-list-enter-active,
::v-deep .el-list-leave-active {
  transition: all 0s;
}

::v-deep .el-list-enter, .el-list-leave-active {
  opacity: 0;
  transform: translateY(0);
}
</style>
